package org.grayrabbit.cloud.core.rpc;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.grayrabbit.cloud.core.handler.Handler;
import org.grayrabbit.cloud.core.mina.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class LocalServer implements Server {
	private final static Logger logger = LoggerFactory
			.getLogger(LocalServer.class);
	private Handler handler;
	private int port = 1053;
	private SocketAcceptor socketAcceptor = new NioSocketAcceptor();

	public LocalServer(int port, Handler handler) {
		this.port = port;
		this.handler = handler;
	}

	public void close() throws ServerException {
		socketAcceptor.dispose();
		logger.info("Server is stopped!");
	}

	public void run() throws ServerException {
		try {

			socketAcceptor.getFilterChain().addLast(
					"codec",
					new ProtocolCodecFilter(
							new ObjectSerializationCodecFactory()));
			socketAcceptor.setHandler(new MessageHandler(handler));
			socketAcceptor.bind(new InetSocketAddress(port));
			logger.info("服务器启动成功,端口:{}", port);
		} catch (IOException e) {
			logger.error("启动服务器异常", e);
			throw new ServerException(e);
		}
	}

}
